package com.zhouyu.exampleSpSource.config;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zhouyu.commonapi.utils.algorithm.AesAlgorithmUtil;
import com.zhouyu.commonapi.utils.algorithm.Decrypt;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.JsonViewRequestBodyAdvice;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

/**
 * Description:请求参数解密
 *
 * @author zhouyu
 * @date 2020/9/3
 * @since 1.0.0
 */
@Component
@RestControllerAdvice(basePackages = "com.zhouyu.exampleSpSource.controller.descontroller")
public class DecryRequestBodyAdvice extends JsonViewRequestBodyAdvice {

    private static Logger logger = LoggerFactory.getLogger(DecryRequestBodyAdvice.class);

    /**
     * Description 该方法用于判断当前请求，是否要执行beforeBodyRead方法
     *
     * @param methodParameter 方法参数
     * @param type            方法的参数类型
     * @param aClass          将会使用到的Http消息转换器类类型
     * @return {@link boolean} 返回true则会执行beforeBodyRead
     * @Author zhouyu
     * @date 2020/9/6 12:47
     **/
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasParameterAnnotation(RequestBody.class);
    }


    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        //String bodyStr = IOUtils.toString(httpInputMessage.getBody(), "utf-8");
        //logger.info("消息体：{}",bodyStr);
        //如果有Decrypt注解
        if (methodParameter.getMethod().isAnnotationPresent(Decrypt.class)) {
            return new HttpInputMessage() {
                @Override
                public InputStream getBody() throws IOException {
                    //解密
                   /* List<String> appIdList = httpInputMessage.getHeaders().get("appId");
                    if (appIdList.isEmpty()) {
                        throw new RuntimeException("请求头缺少appID");
                    }
                    String appId = appIdList.get(0);*/
                    //TODO 根据appid查找秘钥
                    try {
                        String bodyStr = IOUtils.toString(httpInputMessage.getBody(), "utf-8");
                        JsonObject jsonObject = new JsonParser().parse(bodyStr).getAsJsonObject();
                        JsonElement jsonElement = jsonObject.get("params");
                        String encrtStr = jsonElement.getAsString();
                        bodyStr = AesAlgorithmUtil.aesDecrypt(encrtStr, "d86d7bab3d6ac01ad9dc6a897652f2d2");
                        InputStream inputStream = IOUtils.toInputStream(bodyStr, "utf-8");
                        return inputStream;
                    } catch (Exception e) {
                        logger.error("解密参数异常", e);
                        return null;
                    }
                }

                @Override
                public HttpHeaders getHeaders() {
                    return httpInputMessage.getHeaders();
                }
            };
        } else {
            return httpInputMessage;
        }
    }

    @Override
    public Object afterBodyRead(Object bodyObj, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return bodyObj;
    }

    @Override
    public Object handleEmptyBody(Object bodyObj, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return bodyObj;
    }
}
